package bookez.view.util;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import bookez.view.bean.UserBean;


public class SercurityFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}//end method destroy

	@Override
	public void doFilter(ServletRequest req, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		log( "Begin authorizing" );
		
		HttpServletRequest httpReq = ( HttpServletRequest ) req;
		
		String contextPath = httpReq.getContextPath();
		String requestUri  = httpReq.getRequestURI();
		
		log( "contextPath: " + contextPath );
		log( "requestUri : " + requestUri );
		
		boolean requestRestrictedResource = contains( requestUri, contextPath );
		boolean isAuthorized = authorize( httpReq );
		
		if( requestRestrictedResource && !isAuthorized ) {
			log( "authorization failed" );
			httpReq.getRequestDispatcher( this.LOGIN_PAGE ).forward( req, response );
		}//end case: reject
		else {
			log( "authorization succeeded" );
			chain.doFilter( req, response );
		}//end case: accept
		
	}//end method doFilter
	

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		// Initialize all restricted resources
		this.restrictedResources = new HashSet<String>();
		this.restrictedResources.add( "/admin/" );
	}//end method init
	
	private boolean contains( String uri, String contextPath ) {
		
		Iterator<String> ite = this.restrictedResources.iterator();
		
		while( ite.hasNext() ) {
			String resource = ite.next();
			
			boolean matched = uri.contains( resource );
			
			if( matched ) { return true; }
		}//end scanning all restricted resources
		
		return false;
	}//end method contains
	
	private boolean authorize ( HttpServletRequest req ) {
		
		UserBean user = ( UserBean ) req.getSession().getAttribute( "userBean" );
		
		if ( user != null  && user.isAuthenticated() ) {
			return true;
		}//end case: user is authenticated
		return false;
		
	}//end method authorize
	
	private void log( String message ) {
		this.logger.debug( message );
	}//end method log
	
	
	// Login page
	private final String LOGIN_PAGE = "index.xhtml";
	
	// A set of restricted resources
	private Set<String> restrictedResources;
	
	// Logger
	private Log logger = LogFactory.getLog( this.getClass() );

}//end class SercurityFilter
